package com.rbac.admin.controller.system;

import com.rbac.admin.entity.system.SysDictField;
import com.rbac.admin.dto.system.ColumnDefinitionDTO;
import com.rbac.admin.service.system.SysDictionaryService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/system/dictionary")
@RequiredArgsConstructor
public class SysDictionaryController {

    private final SysDictionaryService dictionaryService;

    @GetMapping("/tables")
    public Map<String, Object> getTables(@RequestParam(required = false) String tableName,
                                         @RequestParam(required = false) String comment) {
        List<Map<String, Object>> list = dictionaryService.getTables(tableName, comment);
        Map<String, Object> res = new HashMap<>();
        res.put("code", 200);
        res.put("message", "success");
        res.put("data", list);
        return res;
    }

    @GetMapping("/tables/{tableName}/columns")
    public Map<String, Object> getColumns(@PathVariable String tableName,
                                          @RequestParam(required = false) String columnName) {
        List<Map<String, Object>> list = dictionaryService.getColumns(tableName, columnName);
        Map<String, Object> res = new HashMap<>();
        res.put("code", 200);
        res.put("message", "success");
        res.put("data", list);
        return res;
    }

    @PostMapping("/fields/batch-save")
    public Map<String, Object> saveFields(@RequestBody List<SysDictField> fields) {
        dictionaryService.saveFields(fields);
        Map<String, Object> res = new HashMap<>();
        res.put("code", 200);
        res.put("message", "success");
        res.put("data", true);
        return res;
    }

  /**
   * 创建业务表
   */
  @PostMapping("/tables/{tableName}")
  public Map<String, Object> createTable(@PathVariable String tableName,
                                         @RequestBody List<ColumnDefinitionDTO> columns,
                                         @RequestParam(required = false) String comment) {
    dictionaryService.createTable(tableName, columns, comment);
    Map<String, Object> res = new HashMap<>();
    res.put("code", 200);
    res.put("message", "success");
    res.put("data", true);
    return res;
  }

  /**
   * 为已存在表新增字段
   */
  @PostMapping("/tables/{tableName}/columns")
  public Map<String, Object> addColumns(@PathVariable String tableName,
                                        @RequestBody List<ColumnDefinitionDTO> columns) {
    dictionaryService.addColumns(tableName, columns);
    Map<String, Object> res = new HashMap<>();
    res.put("code", 200);
    res.put("message", "success");
    res.put("data", true);
    return res;
  }
}


